import 'dart:convert';

import 'package:base_flutter/base_flutter.dart' as b;
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:ls_work/a_elder/models/code_value_entity.dart';
import 'package:ls_work/a_elder/models/elder_entity.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/click_item.dart';
import 'package:ls_work/widgets/input_text_page.dart';



class TakeLeaveAddPage extends StatefulWidget {
  final ElderInfo? elderModel;
  final VoidCallback? callBack;
  TakeLeaveAddPage({Key? key, this.elderModel, this.callBack});
  @override
  _TakeLeaveAddPageState createState() => _TakeLeaveAddPageState();
}

class _TakeLeaveAddPageState extends State<TakeLeaveAddPage> {
  TextEditingController _textFieldEditer = TextEditingController();
  List<CodeValue> _familyList = [];
  List<CodeValue> _reasonList = [];
  List<CodeValue> _relationshipList = [];
  int _groupValue = 1;
  String _leaveTime = '';
  String _backTime = '';
  DateTime? _leaveDateTime;
  DateTime? _backDateTime;
  String _reasonStr = '';
  int _reasonId = 0;
  String _familyName = '';
  int _familyId = 0;
  String _familyPhone = '';
  String _relationshipName = '';
  String _relationshipId = '';

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fectcodeType(codeTypeId: 29);
      _fectcodeType(codeTypeId: 5);
      _fectCustomerFamily();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("请假登记"),
        elevation: 0.5,
        actions: [
          TextButton(
            onPressed: _send,
            child: Text(
              '提交',
              style: TextStyle(fontSize: 16, color: Colours.app_main),
            ),
          )
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ClickItem(
              title: "*外出时间：",
              content: _leaveTime,
              onTap: () {
                _showTimePicker(type: 0);
              },
            ),
            ClickItem(
              title: "*预计返回时间：",
              content: _backTime,
              onTap: () {
                _showTimePicker(type: 1);
              },
            ),
            ClickItem(
              title: "*外出事由：",
              content: _reasonStr,
              onTap: () {
                _bottomGoReasonSheetAlert(type: 0, dataList: _reasonList);
              },
            ),
            Container(
              margin: const EdgeInsets.only(left: 15.0),
              padding: EdgeInsets.fromLTRB(0, 5, 20, 5),
              decoration: BoxDecoration(
                border: Border(
                  bottom: Divider.createBorderSide(
                    context,
                    color: Colours.line,
                    width: 1,
                  ),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Expanded(
                    child: Text(
                      '*陪同类型',
                      style: TextStyle(color: Colours.text_dark, fontSize: 16),
                    ),
                  ),
                  Radio(
                    value: 1,
                    groupValue: _groupValue,
                    onChanged: (value) {
                      setState(() {
                        _groupValue = value!;
                      });
                    },
                  ),
                  Text('家属'),
                  Radio(
                    value: 2,
                    groupValue: _groupValue,
                    onChanged: (value) {
                      setState(() {
                        _groupValue = value!;
                      });
                    },
                  ),
                  Text('其他'),
                ],
              ),
            ),
            ClickItem(
              title: "*陪同家属：",
              content: _familyName,
              onTap: () {
                if (_groupValue == 1) {
                  _bottomGoReasonSheetAlert(type: 1, dataList: _familyList);
                } else {
                  AppNavigator.push(
                    context,
                    InputTextPage(
                      title: '陪同人员姓名',
                      content: _familyName,
                      hintText: '请输入陪同人员姓名',
                      keyboardType: TextInputType.number,
                      onPress: (result) {
                        setState(() {
                          _familyName = result;
                        });
                      },
                    ),
                  );
                }
              },
            ),
            ClickItem(
                title: "*家属电话",
                content: _familyPhone,
                onTap: () {
                  AppNavigator.push(
                    context,
                    InputTextPage(
                      title: '家属电话',
                      content: _familyPhone,
                      hintText: '请输入家属电话',
                      keyboardType: TextInputType.number,
                      onPress: (result) {
                        setState(() {
                          _familyPhone = result;
                        });
                      },
                    ),
                  );
                }),
            ClickItem(
              title: "*关系：",
              content: _relationshipName,
              onTap: () {
                if (_groupValue == 2) {
                  _bottomGoReasonSheetAlert(
                      type: 2, dataList: _relationshipList);
                }
              },
            ),
            Gaps.vGap15,
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  '   备注',
                  style: TextStyles.textGray18,
                ),
                Container(
                  padding: EdgeInsets.fromLTRB(20, 0, 20, 20),
                  alignment: Alignment.topLeft,
                  height: 150,
                  width: ScreenUtil.getScreenW(context) - 60,
                  child: TextField(
                    controller: _textFieldEditer,
                    maxLines: 5,
                    autofocus: false,
                    decoration: InputDecoration(
                      hintText: "请输入备注内容",
                      hintMaxLines: 20,
                      fillColor: Colours.bg_color,
                      filled: true,
                      border: InputBorder.none,
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  ///提交数据
  _send() {
    if (_leaveTime.isEmpty) {
      Toast.show("请选择外出时间");
      return;
    }
    if (_backTime.isEmpty) {
      Toast.show("请选择返回时间");
      return;
    }
    if (_reasonStr.isEmpty) {
      Toast.show("请选择外出事由");
      return;
    }
    if (_familyName.isEmpty) {
      Toast.show("请选输入家属姓名");
      return;
    }
    if (_familyPhone.isEmpty) {
      Toast.show("请输入家属电话");
      return;
    }
    SVProgressHUD page = SVProgressHUD(context);
    Map<String, dynamic> map = {
      'customerElderId': widget.elderModel?.id,
      "leaveTime":
          DateUtil.formatDate(_leaveDateTime, format: DateFormats.full),
      "planBackTime":
          DateUtil.formatDate(_backDateTime, format: DateFormats.full),
      "leaveReasonId": _reasonId,
      "accompanyType": _groupValue,
      "accompanyName": _familyName,
      "accompanyMobile": _familyPhone,
      "relationshipId": _relationshipId,
      "leaveRemark": _textFieldEditer.text,
    };
    if (_groupValue == 1) {
      map["accompanyId"] = _familyId;
    }
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.createLeave}?${requestParams(map)}') //
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          if(widget.callBack!=null){
            widget.callBack!();
          }
          Navigator.of(context).pop();
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///家属列表
  _fectCustomerFamily() {
    SVProgressHUD page = SVProgressHUD(context);
    Map<String, dynamic> map = {'customerId': widget.elderModel?.id};
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.customerFamily}', data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          CodeValueEntity model = CodeValueEntity.fromJson(map["data"]);
          if ((model.rows??[]).length > 0) {
            setState(() {
              _familyList = model.rows??[];
              _familyName = model.rows!.first.name;
              _familyId = model.rows!.first.id!;
              _familyPhone = model.rows!.first!.mobile??"";
              _relationshipId = model.rows!.first.relationshipId.toString();
              _relationshipName = model.rows!.first.relationshipName??"";
            });
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///外出事由
  _fectcodeType({int? codeTypeId}) async {
    var map = {'codeTypeId': codeTypeId};
    SVProgressHUD page = SVProgressHUD(context);
    HttpUtil.instance
        .getDio()
        .post(HttpApi.mapType, data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());

        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            CodeValueEntity model = CodeValueEntity.fromJson(map['data']);
            if ((model.rows??[]).length > 0) {
              setState(() {
                if (codeTypeId == 29) {
                  _reasonList = model.rows??[];
                } else if (codeTypeId == 5) {
                  _relationshipList = model.rows??[];
                }
              });
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///外出事由 - 家属列表
  _bottomGoReasonSheetAlert({int? type, List<CodeValue>? dataList}) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (BuildContext context) {
        return SingleChildScrollView(
          child: Container(
            width: double.infinity,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: (dataList??[]).map((f) {
                return ListTile(
                  title: Text(type != 1 ? f.nameCn??"" : f.name??""),
                  onTap: () {
                    setState(() {
                      if (type == 0) {
                        _reasonStr = f.nameCn??"";
                        _reasonId = f.id??0;
                      } else if (type == 1) {
                        _familyName = f.name;
                        _familyId = f.id??0;
                        _familyPhone = f.mobile??"";
                        _relationshipId = f.relationshipId.toString();
                        _relationshipName = f.relationshipName??"";
                        print(_relationshipId);
                      } else if (type == 2) {
                        _relationshipName = f.nameCn??"";
                        _relationshipId = f.codeValue??"";
                      }
                    });
                    Navigator.pop(context);
                  },
                );
              }).toList(),
            ),
          ),
        );
      },
    );
  }

  //调起时间选择器
  _showTimePicker({int? type}) {
    DatePicker.showDatePicker(
      context,
      minDateTime: DateTime.parse("1900-01-01 00:00"),
      maxDateTime: DateTime.parse("2099-01-01 00:00"),
      initialDateTime: DateTime.now(),
      dateFormat: "yyyy-MM-dd HH:mm",
      locale: DateTimePickerLocale.zh_cn,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        confirm: Text('确定'),
      ),
      pickerMode: DateTimePickerMode.datetime,
      onConfirm: (dateTime, List<int> index) {
        if (dateTime == null) {
          return;
        }
        if (type == 0) {
          _leaveDateTime = dateTime;
          setState(() {
            _leaveTime =
                DateUtil.formatDate(dateTime, format: 'yyyy-MM-dd HH:mm');
          });
        } else {
          _backDateTime = dateTime;
          setState(() {
            _backTime =
                DateUtil.formatDate(dateTime, format: 'yyyy-MM-dd HH:mm');
          });
        }
        if (_leaveDateTime != null && _backDateTime != null) {
          if (_leaveDateTime!.isAfter(_backDateTime!)) {
            _backTime = '';
            Toast.show("返院确认时间，不得小于离院时间");
            return;
          }
        }
      },
    );
  }
}
